/*--------------------------------------------------------------------------
Modified from GNU Group's SDCC
Only for study purpose
---------------------------------------------------------------------------*/

#include "common.h"
#include "utils.h"
#include "string.h"

unsigned char hexEscape (const char **src)
{
  char *s ;
  unsigned long value ;

  (*src)++ ;    /* Skip over the 'x' */

  value = strtol (*src, &s, 16);

  if (s == *src)
    {
      // no valid hex found
      //werror(E_INVALID_HEX);
		printf("Error: E_INVALID_HEX, invalid hex character");
    }
  else
    {
      if (value > 255)
        {
          //werror(W_ESC_SEQ_OOR_FOR_CHAR);
			printf("Error: W_ESC_SEQ_OOR_FOR_CHAR");
        }
    }
  *src = s;

  return (char) value;
}

/*------------------------------------------------------------------*/
/* octalEscape - process an octal constant of max three digits      */
/* return the octal value, throw a warning for illegal octal        */
/* adjust src to point at the last proccesed char                   */
/*------------------------------------------------------------------*/

unsigned char octalEscape (const char **str)
{
  int digits;
  unsigned value=0;

  for (digits = 0; digits < 3; digits++)
    {
      if (**str >='0' && **str <= '7')
        {
          value = value*8 + (**str - '0');
          (*str)++;
        }
      else
        {
          break;
        }
    }
  if (digits)
    {
      if (value > 255 /* || (**str>='0' && **str<='7') */ )
        {
          //werror (W_ESC_SEQ_OOR_FOR_CHAR);
			printf("Error: W_ESC_SEQ_OOR_FOR_CHAR");
        }
    }
  return value;
}

/* strncpy() with guaranteed NULL termination. */
char *strncpyz(char *dest, const char *src, size_t n)
{
    assert(n > 0);

    --n;
    /* paranoia... */
    if (strlen(src) > n)
    {
	fprintf(stderr, "strncpyz prevented buffer overrun!\n");
    }
    
    strncpy(dest, src, n);
    dest[n] = 0;
    return dest;
}

/*------------------------------------------------------------------*/
/* preProcess state													*/
/*------------------------------------------------------------------*/
void buildCmdLinePre(char *pbuffer, size_t len, char *pcmdApp, char *filename)
{
	va_list ap;
	char * preCmd = (char *)Safe_alloc(MAX_STRING_LEN);

	/* check command line */
	assert(pbuffer && pcmdApp && filename);  

	/* make command line */
	strcpy(preCmd, pcmdApp);
	strcat(preCmd, " ");
	strcat(preCmd, filename);

	va_start(ap, preCmd);
	va_end(ap);

	strncpyz(pbuffer, preCmd, len);
	Safe_free(preCmd);
}